<script setup>
import {defineProps, ref, defineEmits, computed, watch} from "vue";

const props = defineProps({
  options: {
    type: Array,
    required: true
  },
  label: {
    type: String,
    default: ''
  },
  required: {
    type: Boolean,
    default: false
  },
  modelValue: {
    type: [Number, String],
    default: ''
  },
  readonly: {
    type: Boolean,
    default: false
  },
  disabled: {
    type: Boolean,
    default: false
  },
  rules: {
    type: Array,
    default: () => []
  },
  defaultValue: {
    type: [Number, String],
    default: null
  }
})
const emit = defineEmits(['update:modelValue']);
const showPopup = ref(false);
const fieldValue = ref('')

const selectedValue = computed({
  get() {
    return props.modelValue ? [props.modelValue] : [];
  },
  set(value) {
    if (!value || value.length === 0) {
      emit('update:modelValue', null);
    } else {
      const result = value[0]; // 假设只选择一个值
      const option = props.options.find(item => item.value === result);

      if (option) {
        fieldValue.value = option.text;
        emit('update:modelValue', result);
      }
    }
  }
});

const pickerValue = computed(() => {
  // 如果有选中值，使用选中值
  if (props.modelValue) {
    return [props.modelValue];
  }
  // 如果没有选中值但有默认值，使用默认值
  if (props.defaultValue !== null) {
    return [props.defaultValue];
  }
  // 否则返回空数组
  return [];
});

// 监听 modelValue 变化，同步到显示字段
watch(() => props.modelValue, (newVal) => {
  if (newVal !== undefined) {
    const option = props.options.find(item => item.value === newVal);
    fieldValue.value = option !== undefined ? option.text : '';
  } else {
    fieldValue.value = '';
  }
}, {immediate: true});

const onOpen = () => {
  if (props.readonly) return;
  showPopup.value = true;
}

const onConfirm = ({selectedValues}) => {
  selectedValue.value = selectedValues; // 设置选中的值到 model 中
  showPopup.value = false; // 关闭 popup
}

</script>

<template>
  <van-field v-model="fieldValue"
             input-align="center"
             :label="label"
             @click="onOpen"
             readonly
             :clickable="!readonly"
             :disabled="disabled"
             :required="required"
             placeholder="请选择"
             :rules="rules"/>
  <van-popup v-model:show="showPopup" position="bottom">
    <van-picker :model-value="pickerValue" :columns="options" @confirm="onConfirm" @cancel="showPopup = false"/>
  </van-popup>
</template>

<style scoped lang="scss">

</style>